<html>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$numAdmKeys = numOfAdmins($usrid);

if (strlen($act=getHttpVal('act', '')) > 0) {

  writeLog('act: '.$act, true);

  if (strcmp($act, 'newkey')==0) { //// Act = Add a Yubikey ////

	$otp = strtolower(getHttpVal('otp', ''));
	addHist($usrid, 'add adm yubikey');

	if (strlen($otp) < 10 || strlen(($err = verifyYubikeyOtp($otp))) > 0) {
		if (strlen($otp) < 10) {
			$err = 'Invalid OTP';
		}
		$_SESSION['alert'] = 'Failed to add the Yubikey! '.$err;
//		writeLog('OTP err: ['.$err.'], otp:'.$otp);
	} else {
		$devId = substr($otp, 0, DEVICE_ID_LEN);		
		$a = getKeyInfo($devId);
		
		if ($a['usrid'] < 0) { // Invalid Yubikey
		
		  $_SESSION['alert'] = 'This Yubikey is not recognized by '.$appurl;
		
		} else if ($_SESSION['client'] != $a['client']) {
					
		  	$_SESSION['alert'] = 'The Yubikey belongs to another client. Log in as another user that owns this Yubikey.';
		  	writeLog('keyid:'.$a['keyid'].' belongs to client '.$a['client'], true);	  			
		     
		} else if ($a['usrid'] == 0) { // This is new, add a new Yubikey
		
		  $pin = getHttpVal('pin', '');
		  $note = getHttpVal('note', '');
		  addNewAdmKeyAndPin($a['keyid'], $pin, $devId, $note, $_SESSION['client']);
		  $_SESSION['alert'] = 'A new Yubikey '.$devId.' added successfully!';
		  $subj = 'A new admin Yubikey (id: '.$devId.') is registered at '.$appurl.' under client '.$usrid;		  
		  if (strlen($note) > 0) {
		  	$subj .= ' ('.$note.')';
		  }
		  keyNotification($_SESSION['email'], $devId, $subj);
		  
		} else if ($usrid != $a['usrid']) {
			
		  	$_SESSION['alert'] = 'The Yubikey belongs to another admin. Log in as another user that owns this Yubikey.';
		    writeLog('usrid:'.$a['usrid'].' belongs to adm '.$a['usrid'], true);
		    			  			 
		} else { // Already added
		
		  $_SESSION['alert'] = 'The Yubikey was already in your admin group.';		  	 
		}
		
		if (strlen($_SESSION['alert']) > 0) {
			addHist($usrid, $_SESSION['alert']);
		}
  	}  
  } else if (strcmp($act, 'upd')==0) { //// Act = Upd a Yubikey ////
  
    if (!isset($_POST['id'])) {
    	$_SESSION['alert'] = 'Select checkboxes of Yubikeys you want to modify.';
    } else {
  	  $ids = $_POST['id'];
	  $count = 0;
	  $i = 0;
	  foreach ($ids as $id) {		
		$note = getHttpVal($id.'_note', '');
		$devId = getHttpVal($id.'_devid', '');
		$keyId = getHttpVal($id.'_keyid', '');
		if (clientOfYubikey($keyId) != $_SESSION['client']) {
			$_SESSION['alert'] = 'Yubikey '.$devId.' belongs to another client!';			
			break;
		} else if (updYubikey($usrid, $id, $devId, getHttpVal($id.'_pin', ''), $note)) {
			$count++;
			keyNotification($_SESSION['email'], $id, 'Admin Yubikey updated! '.$note);
			addHist($usrid, 'Admin Yubikey '.$id.' updated!');
		}
	  }
	  if ($count > 0) {
	    $_SESSION['alert'] = 'Updated '.$count. ' admin Yubikey(s) successfully.';
	  }
	}
  
  } else if (strcmp($act, 'del')==0) { //// Act = Del a Yubikey ////
  
  	$ids = $_POST['id'];
  	if (sizeof($ids)==0) {
	  $_SESSION['alert'] = 'Select checkboxes of Yubikeys you want to delete.';
	} else {
  	  $count = 0;
	  foreach ($ids as $id) {
		if (delAdmin($id)) {
			$count++;
			addHist($usrid, 'Deleted admin '.$id);
			if (($numAdmKeys - $count) <= 1) {
				break;
			}
		}
	  }
	  if ( $count > 0) {
	    $_SESSION['alert'] = 'Deleted '.$count.($count>1?' Yubikeys':' Yubikey').' successfully';
	  }
	}
  }
  
  header('Location: index.php');
  exit;

} //// End of performing action

?>

<div align=left><img src=images/arrow.jpg>
<font color=#008080 size=2><b>
You are an admin of the
<?php echo $usrid==1?'root':'Client-'.$_SESSION['client'];?> account, read me first:
</b></font>

<font size=2><ol>
<li>An admin can add other Yubikeys to this admin group so they can log in here to manage Yubikeys
and retrieve secret information.
<p><li>Issue backup admin Yubikeys and keep them in the safe to avoid losing access to this management console.
<p><li>Keep your admin Yubikey safe and we recommend only use it to access Yubico sites.
</ol>
</div>
</font>

</a>
<div id=yubiconsole> </div>

<hr size=1>

<div align=left><font size=2>
<form id=keymgmt name=keymgmt method=post action=yubi_mgmt.php>
<input name=act type=hidden value=''>
<?php
$_SESSION['tab'] = 2;
$n = showMyYubikeys($usrid);
?>

<p>

<?php if ($n > 0): ?>

&nbsp;&nbsp;&nbsp;

 <input type=button class=buttonLinkO value="Update" onClick="submitKeyMgmtForm('upd')">

 <?php if ($numAdmKeys > 1): ?>
 <input type=button class=buttonLinkO value="Delete" onClick="submitKeyMgmtForm('del')">
 <?php endif; ?>
 <p><br>
<?php endif; ?>

</form><!-- End keymgmt form -->

<p>
<div align=left><font size=2><img src=images/arrow.jpg>
<a name=DOWN></a>
<a href=#DOWN onclick="javascript:showAddKey();"><b>Add another Yubikey to my admin group</b>&nbsp; >></a>
</font></div>
<p><div id=addkey> </div>
 
<p><br>
<div align=left><font size=2><img src=images/arrow.jpg>
<a target=_new href=<?php echo YUBICO_AFF_LINK;?>><b>Order Yubikeys</b>&nbsp; >></a>
</font></div>

<?php

function showMyYubikeys($myUsrId) {
  $stmt = 'SELECT a.id, a.note, a.keyid, a.pin, a.last_access, y.tokenId' .
  	' FROM admin a, yubikeys y WHERE a.client='.$_SESSION['client'].' AND y.id=a.keyid';
  $r = query($stmt);
  if (($n=mysql_num_rows($r)) > 0) {
  	echo '<img src="images/yubiright_16x16.gif"> <font color=#008080><b>Yubikeys in the admin group</b></font> '.
  		'(check the Yubikey ID boxes to update/delete keys)<p>';
  		
  	echo '<table cellspacing=2 cellpadding=3><tr bgcolor=#ADFF2F><th width=10 bgcolor=white></th>'.
		'<th align=center><font size=1>Yubikey ID</font></th>'.
		'<th bgcolor=white></th>'.
		'<th align=center><font size=1>Note</font></th>'.
		'<th align=center><font size=1>Password</font></th>'.
		'<th align=center><font size=1>Last Login</font></th></tr>';
  
    while ($row=mysql_fetch_assoc($r)) {
	  $devid = b64ToModhex($row['tokenId']);
	  $adminID = $row['id'];
	  $pin = aesDecrypt($row['pin']);
	  $keyid = $row['keyid'];
	  echo '<input type=hidden name='.$adminID.'_devid value='.$devid.'>'.
	  	'<input type=hidden name='.$adminID.'_keyid value='.$keyid.'>';

	  echo '<tr><td></td><td bgcolor=#ffffff><font size=1>'.
	  	'<input type=checkbox name="id[]" value='.$adminID.'>'.$devid.
		'</td><td width=3></td>';
	  echo '<td><font size=1>'.
	    '<input class=inputtxt size=20 maxlength=45 name='.$adminID.'_note value="'.$row['note'].'"></td>';
	  echo '<td><font size=1>'.
  	    '<input type=password class=inputtxt size=20 maxlength='.PW_MAX.' name='.$adminID.'_pin value="'.$pin.'"';
//  	  if ($myUsrId != $adminID) {
//  	  	echo ' type=password';
//  	  }
	  echo '></td>';
	  echo '<td><font size=1>'.$row['last_access'].'</td>';
	  echo '</tr>';
 	}

    if ($n > 0) {
  		mysql_free_result($r);
  		echo '</table>';
  	}
  }
  
  return $n;

} // End showMyYubikeys

function keyNotification($email, $devId, $subj) {
	global $admEmail;
	sendMail($email, $subj, 'Yubikey ID: '.$devId."\n", $admEmail);
}
?>

</body>
</html>
